class UserController {
    
	def index = {}

	def login = {
		if(session.user) {
			redirectToAppropriateControllerAndAction()
		}
	}
	
	def handleLogin = {
		def user = User.findByName(params.name)
		if (user) {
			if (user.encryptedPassword == params.password.encodeAsEncryptedPassword()) {
				session.user = user
				redirectToAppropriateControllerAndAction()
			}
			else {
				handleInvalidLogin()
			}
		}
		else {
			handleInvalidLogin()
		}
	}
	
	def handleLogout = {
		if(session.user) {
			session.user = null
		}
		redirect(action:login)
	}
	
	//Just renders the "register" view
	def register = {}
	
	def handleRegistration = {
		def user = new User(params)
		if (params.password != params.confirm) {
			flash.message = "The passwords you entered do not match."
			redirect(action:register)
		}
		else {
			user.encryptedPassword = params.password.encodeAsEncryptedPassword()
			if (user.save()) {
				//Probably it's better to redirect to 'home' of the site instead of requiring a login just after registration
				redirect(action:login)
			}
			else {
				render(view:'register', model:[user:user])
			}
		}
	}
	
	private def redirectToAppropriateControllerAndAction() {
		def redirectParams = session.originalRequestParams ? session.originalRequestParams : [controller:'softwareIdea',  action:'list'] 
		session.originalRequestParams = null
		redirect(redirectParams)
	}
	
	private def handleInvalidLogin() {
		flash.message = "Incorrect login/password combination for user ${params.name}. Please try again."
		redirect(action:login)
	}
}